<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Cache;
use think\facade\Event;
use think\Model;

class User extends Base
{

    protected $name = 'user';

    protected $type = [
        'active_time' => 'timestamp',
    ];

    protected function level()
    {
        return $this->hasOne(Level::class, 'id', 'level_id');
    }

    protected function team()
    {
        return $this->hasOne(TeamLevel::class, 'id', 'team_id');
    }

    public function shop()
    {
        return $this->hasOne(Shop::class, 'id', 'shop_id')->field('id,title');
    }

    public function assets()
    {
        return $this->hasOne(Assets::class, 'uid');
    }

    public function getNicknameAttr($value)
    {
        return $value ?: Cache::get('system')['default_nickname'];
    }

    public function getPhotoAttr($value)
    {
        return $value ?: Cache::get('system')['default_photo'];
    }

    protected function getMinTeamAttr($value, $data)
    {
        return self::geMinTeam($data['id']);
    }

    public static function _save($param, $logs)
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $original = self::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    return ['code' => -1, 'msg' => '记录不存在，请检查！'];
                }
                $logs['original'] = $original;
                $model = self::update($param);
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
//                $count = parent::where(['code' => $param['code']])->count();
//                if ($count) {
//                    return ['code' => -1, 'msg' => '会员编号已被注册'];
//                }
                $code =  rand(100000, 999999);
                while(User::where(['code'=>$code])->find()){
                    $code =  rand(100000, 999999);
                }
                $count = parent::where(['mobile' => $param['mobile']])->count();
                if ($count) {
                    return ['code' => -1, 'msg' => '手机号已被注册'];
                }
                $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2])->find();
                if (empty($parent)) {
                    return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                }
                $node = parent::where(['code' => $param['node_code'], 'is_active' => 2])->find();
                if (empty($node)) {
                    return ['code' => -1, 'msg' => '接点人不存在或未激活'];
                }
                $shop = parent::where(['code' => $param['recommend_shop'], 'is_shop' => 1])->find();
                if (empty($shop)) {
                    return ['code' => -1, 'msg' => '店铺不存在'];
                }
                $param['code'] = $code;
                $param['mobile'] = trim($param['mobile']);
                $param['parent_id'] = $parent->id;
                $param['parent_name'] = $parent->nickname;
                $param['node_id'] = $node->id;
                $param['node_name'] = $node->nickname;
                $param['recommend_shop_id'] = $shop->id;
                $param['password'] = !empty($param['password']) ? md5($param['password']) : md5('111111');
                $param['pay_password'] = !empty($param['pay_password']) ? md5($param['pay_password']) : md5('222222');
                parent::create($param);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功', 'url' => url('login/index')->build()];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _miniAppletSave($mobile)
    {
        try {
            $info = parent::where('mobile', $mobile)->where('is_del', 0)->find();
            $token = md5($mobile . time());
            if ($info) {
                $info->last_time = time();
                $info->last_ip = request()->ip();
                $info->token = $token;
                $info->save();
            } else {
                $update['mobile'] = $mobile;
                $update['last_time'] = time();
                $update['last_ip'] = request()->ip();
                $update['token'] = $token;
                $update['code'] = generate(6, '', 2);
                parent::create($update);

                Event::trigger('Statistics', ['key' => 'user', 'value' => 1]);
            }
            return ['code' => 1, 'msg' => '登录成功', 'data' => ['token' => $token]];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _miniAppletEdit($param, $user)
    {
        parent::startTrans();
        try {

            if (isset($param['nickname']) && $param['nickname']) {
                $user->nickname = $param['nickname'];
            }

            if (isset($param['photo']) && $param['photo']) {
                $user->photo = $param['photo'];
            }
            if (isset($param['mobile']) && $param['mobile']) {
                if (!$user->mobile) {
                    $user->mobile = $param['mobile'];
                }
            }
            if (isset($param['parent_code']) && $param['parent_code']) {
                if (!$user->parent_code) {
                    $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2, 'is_del' => 0])->find();
                    if (empty($parent)) {
                        return ['code' => -1, 'msg' => '推荐人不存在或未激活'];
                    }
                    $user->parent_id = $parent->id;
                    $user->parent_name = $parent->nickname;
                    $user->parent_code = $parent->code;
                    $res = (new Relation())->record($user->id, $user->code, $param['parent_code'], $user->parent_id);
                    if ($res['code'] != 1) {
                        parent::rollback();
                        return ['code' => 1, 'msg' => '加载失败'];
                    }
                }
            }

            $user->save();
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function onAfterInsert($user)
    {

        if ($user->parent_code) {
            (new Relation())->record($user->id, $user->code, $user->parent_id);
        }
        if ($user->node_code) {
            (new Node())->record($user->id, $user->code, $user->node_id);
        }
        $user->assets()->save(['uid' => $user->id]);
    }


    public static function recharge($param, $admin)
    {
        try {
            parent::startTrans();
            try {
                $user = parent::find($param['id']);
                if ($user->isEmpty()) {
                    return json(['code' => -1, 'msg' => '未查询到相关会员']);
                }
                $account = get_pay_way($param['account']);
                if ($param['mode'] == 1) {
                    Target::Account()
                        ->basics($param['id'], $param['account'], $param['amount'],$param['amount'], '后台充值', '+')
                        ->setMsg($param['remarks'])
                        ->createRecharge();
                    $logs = '后台充值【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
                } else {
                    Target::Account()
                        ->basics($param['id'], $param['account'], $param['amount'],$param['amount'], '后台扣除', '-')
                        ->setMsg($param['remarks'])
                        ->createRecharge();
                    $logs = '后台扣除【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
                }

                Logs::adds($logs, $admin['id'], $admin['admin_name']);

                parent::commit();
                return json(['code' => 1, 'msg' => '操作成功']);

            } catch (\Exception $e) {
                parent::rollback();
                return json(['code' => -1, 'msg' => $e->getMessage()]);
            }


        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }


    public static function security($param, $user, $first = false): array
    {
        try {
            $pass = $param['type'];
            $msg = '已设置';
            if (!$first) {
                if (md5($param['old_password']) != $user->$pass) {
                    return ['code' => -1, 'msg' => '旧密码错误'];
                }
                if (md5($param['old_password']) == md5($param['password'])) {
                    return ['code' => -1, 'msg' => '新旧密码相同'];
                }
                $msg = '已修改';

            }

            $user->$pass = md5($param['password']);
            if ($pass == 'password') {
                $user->token = md5(time() . json_encode($user));
                cookie('token', null);
            }
            $user->save();

            return ['code' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function geMinTeam($uid)
    {
        $areaData = parent::where('parent_id', $uid)->order('team_total', 'desc')->column('my_total+team_total as team_total');
        if ($areaData) {
            array_shift($areaData);
            if (!empty($areaData)) return array_sum($areaData);
        }
        return 0;
    }

}
